/*************************************************
 * File:    		SMJS.cpp
 * Author:  	HouJiong <hou_jiong@163.com>
 * Brief:   		StoneMoneky project.
 *
 * Copyright (c) HouJiong
 *
 *************************************************/

/*
 * History:
 * =======================================
 * 2009-04-10 HouJiong <hou_jiong@163.com> created
 */
 
#include "SMJS.h"
#include "SMJS_function.h"
#include "SMJS_Document.h"


JSClass globalClass = 
{
  "Global", 0,
  JS_PropertyStub,  JS_PropertyStub,JS_PropertyStub, JS_PropertyStub,
  JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub,  JS_FinalizeStub
};

SMJS::SMJS()
{
	rt=NULL;
	cx=NULL;
	globalObj=NULL;
}

SMJS::~SMJS()
{

}

bool SMJS::loadJS(std::string jsfile)
{
	rt = JS_Init(1000000L);	
	if(rt==NULL )
	{
		DEBUG_ERROR();
		return false;
	}
	
	cx = JS_NewContext(rt, 8192);
	if(cx==NULL)
	{
		DEBUG_ERROR();
		return false;
	}
	
	globalObj = JS_NewObject(cx, &globalClass, 0, 0);		
	if(globalObj==NULL)
	{
		DEBUG_ERROR();
		return false;
	}

	registerJS();
	
	JSString *str;	
	std::string script;
	std::string buffer;
	std::ifstream istr(jsfile.c_str());
	if ( istr.is_open() )
	{
		do
		{
			std::getline(istr, buffer);
			script += buffer;
		} while (!istr.fail());
	}
	else
	{
		DEBUG_ERROR();
		return false;
	}
		
	jsval rval;	
	uintN lineno = 0;
	JSBool ok = JS_EvaluateScript(cx, globalObj, script.c_str(), script.length(), jsfile.c_str(), lineno, &rval);

	return true;
}

void SMJS::registerJS()
{
	JS_DefineFunction(cx, globalObj, "print", print, 2, 0);	
	JSDocument::JSInit(cx, globalObj);
}

void SMJS::callback(std::string func)
{
	jsval rval;	
	JS_CallFunctionName(cx, globalObj, func.c_str(), 0, 0, &rval);
}
